# -*- coding: utf-8 -*-

import json
import logging

from flask import Flask, request,jsonify

from app.init import Init
from app.keyword.keyword_extract import KeywordExtract
from app.common.config import Config
import base64
import sys
import traceback

app = Flask(__name__)

@app.route("/")
def index():
    return "Congratulations!"

@app.route("/keyword_sentences", methods=['GET', 'POST'])
def keyWordSentences():
    logging.debug("api /keyword_sentences was invoked...")
    url = ''
    try:
        if request.method == 'GET':
            # 默认都是通过 url传参
            url = request.args.get('url', '')
            if url == '':
                url = request.form.get('url', '')
        else:
            url = request.form['url']

        if url == '':
            data =  {"code": -1,"message":"You must give the parameter url"}
            return jsonify(data)

        #对url 进行 base64 解码
        #url = base64.b64decode(url)

        config = Config('config.ini')
        keywordService = KeywordExtract(config.get('other', 'stopwordsFilePath'))
        title, keyword, keySentences = keywordService.keyWordSentencesByUrl(url, 3)
        category = 'unkown'
        data = {"code": 1,"message":"success","data":{"title": title, "keyword": keyword, "keySentences": keySentences, "category": category}}
    except IOError:
        logging.error("IOError",url)
    except:
        logging.error('api /keyword_sentences exception', sys.exc_info())

    # 可以解决中文问题
    return json.dumps(data,ensure_ascii=False)

if __name__ == "__main__":
    Init()
    app.debug = True
    app.run( host="0.0.0.0",port=int("3002"))